local skynet    = require "skynet.manager"
local httpc     = require "http.httpc"
local cjson     = require "cjson"
local util      = require "util"
local md5       = require "md5"
local hosts     = require "hosts"

local service_class = require "service_class"
local constant = require "constant"
local server_config = dofile(skynet.getenv("server_config"))


local string_format = string.format

local web_proxy = class("web_proxy",service_class)

--------------------------
function web_proxy:ctor()
    self.host_name = server_config.webserver_url
    httpc.timeout = 10 * 100
    --httpc.dns(server_config.dns_address, server_config.dns_port)
    self:parse_hosts()
end

function web_proxy:reload() 
end

function web_proxy:parse_hosts() 
    self.host_name = hosts.resolve(server_config.webserver_url)
    self.go_host_name = hosts.resolve(server_config.go_webserver_url)
    print("parse_hosts",tostring_r(hosts.parse_hosts()))
    return true
end

function web_proxy:web_post(url, data, exheader, go_host)
    exheader = exheader or {}
    local exchange_url = url

    local host_name = self.host_name
    if go_host then 
        host_name = self.go_host_name
    end
    dbglog("_________web_post__", url, data)

    local uid = exheader.uid or -1
    local effect_time = util.get_now_time()
    local sign = md5.sumhexa(string.format("%d%d%s",uid,effect_time,constant.internal_key or ''))
    local headers = {
        sign=sign,uid=uid,time=effect_time,
        ['HTTP-CLIENT-IP'] = util.inet_ntoa(exheader.ip or 0),
        ['Client-ChannelId']= exheader.channel,
        ['Client-VersionId'] = exheader.client_version,
        ['Client-Device'] = exheader.device_brand,
        ['Client-MachineCode'] = exheader.device_id,
        ['account-id'] = exheader.account_id or -1,
        ['Client-System'] = exheader.os_system or '',
        ['Client-Platform'] = exheader.platfrom or '',
        ['content-type'] = exheader.content_type or 'application/json',
        ['Current-System'] = exheader.current_system or '',

    }

    local status,body = httpc.request('POST', host_name,exchange_url,nil,headers,data)

    dbglog("requst-->web_post status:",status,", url:", host_name,exchange_url,", body",tostring_r(data),", header", tostring_r(headers))
    if status ~= 200 then
        errlog('failed to web_proxy',status,tostring_r(body))
        return status,nil
    end

    if not body then
        errlog('web_proxy invalid response',body)
        return -100,nil
    end

    dbglog("relay-->web_post url:", host_name,exchange_url,",body",tostring_r(body))
    return status,body
end

return web_proxy

